# -*- coding: utf-8 -*-

"""
Created on Fri Jun  8 18:43:24 2018

@author: Administrator
"""
#%%
import os
import glob
from nilearn.input_data import NiftiMasker
import pandas as pd
from scipy import stats
from ..plot import Boxplot
from ..origin import Basic_str
#%%

class Extract_region_average_correlate(Basic_str):
  def __init__(self,input_list):
    print('---------------------------------------------------')
    print('in the Extract_region_average')
    if len(input_list) != 3 :
        raise Exception("the number of elements of input_list is not equal to 3")
    self.initialize_parameters(input_list)
    self.across_subject_single_region_correlate()
  def initialize_parameters(self,input_list):
    ##########################################################################重新整理传入参数
    self.group1_filepaths = input_list[0]
    self.group2_filepaths = input_list[1]
    self.mask_filepaths = input_list[2]
    
  def across_subject_single_region_correlate(self):
    group1regionmean_list = []
    group2regionmean_list = []
    for group1_filepath,group2_filepath,mask_filepath in zip(self.group1_filepaths,self.group2_filepaths,self.mask_filepaths):
      print('group1_filepath:',group1_filepath)
      print('group2_filepath:',group2_filepath)
      print('mask_filepath:',mask_filepath)
      groupmask = NiftiMasker(mask_img=mask_filepath)
      group1file_masked = groupmask.fit_transform(group1_filepath)
      group2file_masked = groupmask.fit_transform(group2_filepath)
      print('dimention of group1file_masked:',group1file_masked.shape)
      print('dimention of group2file_masked:',group2file_masked.shape)
      group1regionmean_list.append(group1file_masked.mean())
      group2regionmean_list.append(group2file_masked.mean())
    
    print('group1regionmean_list:',group1regionmean_list)
    print('group2regionmean_list:',group2regionmean_list)
    self.cor_coeff = list(stats.pearsonr(group1regionmean_list,group2regionmean_list))
    print('self.cor_coeff:',self.cor_coeff)
#%%
        
class Across_subject_region_average_correlate(Basic_str):
  #作用原理：for instance:对30个subject PET_z CBF_z做cross voxel analysis，and store the result as excel and picture
  #参数说明：
  #参数说明：
  #返回值说明：
  #举例：
  #调用：
  #被调用：
  #bug：
  
  #below are necessary strings
  def __init__(self,input_list,column_name_list,item):
#    print('in the Volume_spatial_correlate')
#    print('input_list:',input_list)
    #test if the input_list has four parameters
    if len(input_list) != 4 :
        raise Exception("the number of elements of input_list is not equal to 4")
    self.initialize_parameters(input_list,column_name_list,item)
    self.across_subject_region_average_correlate()
      
  def initialize_parameters(self,input_list,column_name_list,item):
      

    #重新整理传入参数
    self.group1_dirpath = input_list[0]
    self.group2_dirpath = input_list[1]
    self.gray_threshold_dirpath = input_list[2]
    self.output_dirpath = input_list[3]
    self.column_name_list = column_name_list
    self.tag = item
    self.gray_tag = os.path.split(self.gray_threshold_dirpath)[1].split(self.linkline)[-1]
#    print('search_path:',self.gray_threshold_dirpath+os.sep+self.star)
    self.gray_region_mask_dirpaths = glob.glob(self.gray_threshold_dirpath+os.sep+self.star)
    self.gray_region_mask_dirpaths.sort()
   
    print('#############################################')
    print('search_path:',self.group1_dirpath+os.sep+self.star_suffix) 
    print('search_path:',self.group2_dirpath+os.sep+self.star_suffix)
    self.group1_filepaths = glob.glob(self.group1_dirpath+os.sep+self.star_suffix)
    self.group2_filepaths = glob.glob(self.group2_dirpath+os.sep+self.star_suffix)
    self.group1_filepaths.sort()
    self.group2_filepaths.sort()
    print('group1_filepaths:',self.group1_filepaths)
    print('group2_filepaths:',self.group2_filepaths)
    if len(self.group1_filepaths) != len(self.group2_filepaths):
        raise Exception("the number of file of group1 is different from that of group2 ")
#    self.fileamount = len(self.group1_filepaths)
#    self.group_correlation = pd.DataFrame(columns=column_name_list)
    self.coeff_pvalue_df = pd.DataFrame(columns=column_name_list)
    
  def across_subject_region_average_correlate(self):
    #parameters used to name the excel and png file
    x = 2
    y = 0
    special_str = r'across_subject_region_average_correlate'
    excel_suffix = '.xlsx'
    graph_suffix = '.png'
    coeff_pvalue_file_str = os.sep + self.gray_tag + self.underline + special_str + excel_suffix
    graph_filename = self.gray_tag + self.underline + special_str + graph_suffix
    
    for mask_dirpath in self.gray_region_mask_dirpaths:
      mask_filepaths = glob.glob(mask_dirpath+os.sep+self.suffix)
      mask_filepaths.sort()
      region = os.path.split(os.path.split(mask_dirpath)[0])[1]
      extract_result = Extract_region_average_correlate([self.group1_filepaths,self.group2_filepaths,mask_filepaths])
      medi = dict(zip(self.column_name_list,extract_result.cor_coeff + [region,self.tag]))
      self.coeff_pvalue_df = self.coeff_pvalue_df.append(medi,ignore_index=True)
      
    #将coeff_pvalue_df存到一个csv文件里
    output_dirpath = self.output_dirpath + os.sep + self.tag.replace(self.os_sep,self.underline)
    if not os.path.exists(output_dirpath):
      os.makedirs(output_dirpath)
    self.coeff_pvalue_df.to_excel(output_dirpath+coeff_pvalue_file_str)
    #plot
    Boxplot(self.coeff_pvalue_df,self.column_name_list,x,y,output_dirpath,graph_filename)
    
#%%
  
class Multi_across_subject_region_average_correlate(Basic_str):
  
  #作用原理：do all kinds of permutation and  use a for-loop to pass them to Volume_spatial_correlate
  #参数说明：
  #参数说明：
  #返回值说明：
  #举例：
  #调用：
  #被调用：
  #bug：
  def __init__(self,input_list):
      #get the input_list
      if len(input_list) != 2 :
          raise Exception("the number of elements of input_list is not equal to 2")
      grouppath_dict = input_list[0]
      column_name_list = input_list[1]
      #begin to caculate
      for item in grouppath_dict.keys():
          print('item:',item)
          print('grouppath_dict[item]:',grouppath_dict[item])
          gray_threshold_mask_dirpaths = glob.glob(grouppath_dict[item][2]+os.sep+self.star)
          for gray_threshold_dirpath in gray_threshold_mask_dirpaths:
            grouppath_dict[item][2] = gray_threshold_dirpath
            Across_subject_region_average_correlate(grouppath_dict[item],column_name_list,item)
      